using System;
using System.Collections.Generic;
using System.Text;
using System.Net.Mail;
using System.Diagnostics;
using System.Windows;
using Ricciolo.PaperBoy.Environment.Properties;
using System.Security.Cryptography;

namespace Ricciolo.PaperBoy.Environment.ExceptionHandling
{
    public class ExceptionManager
    {

        private static ExceptionManager _manager = new ExceptionManager();
        private Queue<Exception> queue = new Queue<Exception>();
        private bool showing;

        private ExceptionManager()
        {
        }

        internal static ExceptionManager Manager
        {
            get { return _manager; }
        }

        private void FatalErrorInternal(Exception e)
        {
            Debug.WriteLine(e.ToString());

            // Add to queue
            lock (queue)
            {
                queue.Enqueue(e);
            }
            if (showing) return;

            // Get exception from queue
            while (queue.Count > 0)
            {
                showing = true;

                e = queue.Dequeue();
                string hash64 = GetExceptionHash(e);

                // If the hash is into the list, skip form
                if (Settings.Default.DisabledMessages != null && Settings.Default.DisabledMessages.Contains(hash64)) return;

                using (NotifyForm nf = new NotifyForm(e))
                {
                    nf.ShowDialog();

                    if (nf.DisableMessage)
                        DisableMessage(e);
                }
            }
            showing = false;
        }

        private void DisableMessage(Exception e)
        {
            string hash64 = GetExceptionHash(e);

            if (Settings.Default.DisabledMessages == null)
                Settings.Default.DisabledMessages = new System.Collections.Specialized.StringCollection();

            // Add hash to the list
            if (!Settings.Default.DisabledMessages.Contains(hash64))
                Settings.Default.DisabledMessages.Add(hash64);
        }

        private string GetExceptionHash(Exception e)
        {
            // Compute hash
            HashAlgorithm algorithm = SHA1.Create();
            byte[] hash = algorithm.ComputeHash(System.Text.Encoding.Unicode.GetBytes(e.ToString()));

            string hash64 = Convert.ToBase64String(hash);
            return hash64;
        }

        private void NormalErrorInternal(Exception e)
        {
            Debug.WriteLine(e.ToString());
            MessageBox.Show(e.Message, "PaperBoy", MessageBoxButton.OK, MessageBoxImage.Error);
        }

        public static void NormalError(Exception e)
        {
            ExceptionManager.Manager.NormalErrorInternal(e);
        }

        public static void FatalError(Exception e)
        {
            ExceptionManager.Manager.FatalErrorInternal(e);
        }
    }
}
